import 'package:flutter/material.dart';

// 全局loading，无需context（需要在app启动的时候设置navigatorKey: GlobalContextHolder.navigatorKey）
class LoadingOverlay {
  static final LoadingOverlay instance = LoadingOverlay._internal();
  LoadingOverlay._internal();

  OverlayEntry? _overlayEntry;
  bool _isShowing = false;

  void show({String message = '加载中...', Color? backgroundColor}) {
    if (_isShowing) return;

    final overlay = GlobalContextHolder.overlay;
    if (overlay == null) return;

    _overlayEntry = OverlayEntry(
      builder: (_) => _LoadingWidget(
        message: message,
        backgroundColor: backgroundColor ?? Colors.black.withAlpha(50),
      ),
    );

    overlay.insert(_overlayEntry!);
    _isShowing = true;
  }

  void hide() {
    if (_isShowing) {
      _overlayEntry?.remove();
      _overlayEntry = null;
      _isShowing = false;
    }
  }
}

class _LoadingWidget extends StatefulWidget {
  final String message;
  final Color backgroundColor;

  const _LoadingWidget({
    required this.message,
    required this.backgroundColor,
  });

  @override
  State<_LoadingWidget> createState() => _LoadingWidgetState();
}

class _LoadingWidgetState extends State<_LoadingWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnim;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _scaleAnim =
        CurvedAnimation(parent: _controller, curve: Curves.easeOutBack);
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: widget.backgroundColor,
      child: Center(
        child: ScaleTransition(
          scale: _scaleAnim,
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const CircularProgressIndicator(),
                const SizedBox(height: 16),
                Text(widget.message, style: const TextStyle(fontSize: 16)),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class GlobalContextHolder {
  static final GlobalKey<NavigatorState> navigatorKey =
      GlobalKey<NavigatorState>();

  static BuildContext? get context => navigatorKey.currentContext;
  static OverlayState? get overlay => navigatorKey.currentState?.overlay;
}
